package com.example.smartcity.ui.more

import android.app.Activity
import android.os.Bundle
import android.util.Log
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.TextView
import androidx.fragment.app.Fragment
import androidx.lifecycle.Observer
import androidx.lifecycle.ViewModelProvider
import androidx.recyclerview.widget.GridLayoutManager
import androidx.recyclerview.widget.LinearLayoutManager
import com.example.smartcity.R
import com.example.smartcity.SmartCityApplication
import com.example.smartcity.databinding.FragmentMoreBinding
import com.example.smartcity.ui.more.Adapter.MoreRecyclerViewAdapter
import com.example.smartcity.ui.more.model.MoreEntity
import okhttp3.internal.notify

class moreFragment : Fragment() {


    private val viewModel by lazy {
        ViewModelProvider(this)[moreViewModel::class.java]
    }

    private var _binding: FragmentMoreBinding? = null

    private val binding get() = _binding!!

    override fun onCreateView(
        inflater: LayoutInflater,
        container: ViewGroup?,
        savedInstanceState: Bundle?
    ): View {
        _binding = FragmentMoreBinding.inflate(inflater, container, false)
        val root: View = binding.root

        // 全部服务
        showMore()

        return root
    }



    override fun onDestroyView() {
        super.onDestroyView()
        _binding = null
    }

    /**
     * 显示所有服务
     */
    private fun showMore(){
        // 存储数据
        val array = ArrayList<MoreEntity>()

        val layout = GridLayoutManager(context, 3)
        binding.moreRecyclerView.layoutManager = layout
        val adapter = MoreRecyclerViewAdapter(array)
        binding.moreRecyclerView.adapter = adapter

        viewModel.more("N")

        // 从viewModel获取数据
        viewModel.moreLiveData.observe(this, Observer { resources ->
            val body = resources.getOrNull()
            if(body != null) apply {
                // 清空数据
                viewModel.moreList.clear()
                // 添加数据
                viewModel.moreList.addAll(body)
            }

            // 取出数据存储到适配器中
            for (i in viewModel.moreList){
                if(array.size < viewModel.moreList.size){
                    array.add(MoreEntity(SmartCityApplication.url + i.imgUrl, i.serviceName))
                    // 刷新数据
                    adapter.notifyItemChanged(array.size)
                }
            }
        })

        // 将布局显示出来
        binding.isMore.visibility = View.VISIBLE
    }
}